import React, {
  useMemo, useState, useEffect, useRef,
} from 'react';
import { observer } from 'mobx-react-lite';
import {
  useFormatCommon, useFormatMessage, Content, Page, Breadcrumb, HeaderButtons, Header,
  ExternalComponent,
} from '@choerodon/master';
// @ts-ignore
import { Loading } from '@zknow/components';
import { Tabs } from 'choerodon-ui/pro';
import { useStore } from './stores/index';
import DingtalkMsgTable from './Components/dingtalkMsgTable';
import './index.less';

export interface Props {

}

const { TabPane } = Tabs;

const PageContent: React.FC<Props> = (props) => {
  const {
    intlPrefix, prefixCls, dingtalkMsgTableDs,
  } = useStore();
  const formatCommon = useFormatCommon();
  const formatMessage = useFormatMessage(intlPrefix);

  const [activeKey, setActiveKey] = useState('dingtalkmsg');
  const [pageLoading, setPageLoading] = useState(true);
  const [hasYamiTable, setHasYamiTable] = useState(false);
  const childRef = useRef<any>();

  const YamiTable = <ExternalComponent cref={childRef} system={{ scope: 'haitianBase', module: 'configuration-base-routes-org-msg-log:yamiMsgTable' }} />;

  useEffect(() => {
    async function asyncFunc() {
      try {
        const res = await (window as any)?.haitianBase?.get('configuration-base-routes-org-msg-log:yamiMsgTable');
        if (res) {
          setHasYamiTable(true);
          setActiveKey('yamimsg');
        }
      } catch (error) {
        console.log(error);
      }
      setPageLoading(false);
    }
    asyncFunc();
  }, []);

  const dingtalkmsgRefresh = () => {
    dingtalkMsgTableDs.query();
  };

  const panes = useMemo(() => {
    const arr = [
      {
        key: 'dingtalkmsg',
        tab: '钉钉日志',
        child: <DingtalkMsgTable />,
        headerBtns: [
          {
            icon: 'refresh',
            handler: dingtalkmsgRefresh,
          },
        ],
      },
    ];

    hasYamiTable && arr.unshift(
      {
        key: 'yamimsg',
        tab: '娅米日志',
        child: YamiTable,
        headerBtns: [
          {
            icon: 'refresh',
            handler: () => { childRef?.current?.yamiTableRefresh(); },
          },
        ],
      },
    );

    return arr;
  }, [hasYamiTable]);

  const tabsChange = (key: string) => {
    if (activeKey !== key) {
      setActiveKey(key);
      const arr = panes[panes.findIndex((i) => i.key === key)].headerBtns;
      arr[arr.length - 1].handler();
    }
  };

  const headerBtns = useMemo(() => () => panes[
    panes.findIndex((i) => i.key === activeKey)].headerBtns, [activeKey]);

  return (
    pageLoading ? <Loading />
      : (
        <Page>
          <Header>
            <HeaderButtons items={headerBtns()} />
          </Header>
          <Breadcrumb />
          <Content className={`${prefixCls}-page-content`}>
            <Tabs activeKey={activeKey} onChange={tabsChange}>
              {panes.map((item: any) => (
                <TabPane key={item.key} tab={item.tab}>
                  {item.child}
                </TabPane>
              ))}
            </Tabs>
          </Content>
        </Page>
      )
  );
};

export default (observer(PageContent));
